package com.gcxy.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.gcxy.constant.StringConst;
import com.gcxy.core.PageVO;
import com.gcxy.core.R;
import com.gcxy.dto.export.DownloadFileDTO;
import com.gcxy.dto.project.ProjectFileDTO;
import com.gcxy.dto.student.StudentPageDTO;
import com.gcxy.entity.Semester;
import com.gcxy.entity.User;
import com.gcxy.entity.UserProject;
import com.gcxy.mapper.SemesterMapper;
import com.gcxy.mapper.UserMapper;
import com.gcxy.mapper.UserProjectMapper;
import com.gcxy.service.ProjectService;
import com.gcxy.entity.Project;
import com.gcxy.mapper.ProjectMapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gcxy.service.StudentService;
import com.gcxy.utils.BeanCopyUtil;
import com.gcxy.utils.ExcelUtil;
import com.gcxy.vo.student.StudentPageVO;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

import java.util.List;
import java.util.stream.Collectors;

import static com.gcxy.constant.StringConst.DEFAULT_FILE_PATH;

/**
 * <p>
 * 项目表 服务实现类
 * </p>
 *
 * @author Huang先森
 * @since 2024-07-22
 */
@Service
public class ProjectServiceImpl extends ServiceImpl<ProjectMapper, Project> implements ProjectService {

    private final ProjectMapper projectMapper;
    private final SemesterMapper semesterMapper;
    private final UserMapper userMapper;
    private final UserProjectMapper userProjectMapper;
    private final StudentService studentService;

    public ProjectServiceImpl(ProjectMapper projectMapper, SemesterMapper semesterMapper, UserMapper userMapper, UserProjectMapper userProjectMapper, StudentService studentService) {
        this.projectMapper = projectMapper;
        this.semesterMapper = semesterMapper;
        this.userMapper = userMapper;
        this.userProjectMapper = userProjectMapper;
        this.studentService = studentService;
    }

    @Override
    public Project getByProjectName(String projectName) {
        LambdaQueryWrapper<Project> queryWrapper = new LambdaQueryWrapper<Project>().eq(Project::getProjectName, projectName);
        return this.getOne(queryWrapper);
    }

    /**
     * 生成项目老师学生清单
     *
     * @param dto
     * @return
     */
    @Override
    public R<?> createProjectStudentListFile(DownloadFileDTO dto) {
        //1.获取参数
        //1.1获取所有项目
        List<User> userList = userMapper.selectList(new LambdaQueryWrapper<User>().eq(User::getAgencyId, dto.getAgencyId()));
        List<ProjectFileDTO> projectFileDTOList = new ArrayList<>();
        if (CollectionUtils.isEmpty(userList)) {
            return R.Failed("文件生成失败！该组织下没有学生可生成数据。");
        }
        List<Integer> userIds = userList.stream().map(User::getId).collect(Collectors.toList());
        //1.2.1根据用户id获取用户对应的项目id
        List<UserProject> userProjects = userProjectMapper.selectList(new LambdaQueryWrapper<UserProject>()
                .eq(UserProject::getSemesterId, dto.getSemesterId())
                .in(UserProject::getUserId, userIds));
        if (CollectionUtils.isEmpty(userProjects)) {
            return R.Failed("文件生成失败！该组织该学期内学生没有项目可生成数据。");
        }
        List<Integer> projectIdList = userProjects.stream().map(UserProject::getProjectId).collect(Collectors.toList());
        //1.2.2根据项目id获取项目
        List<Project> list = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(projectIdList)) {
            list = list(new LambdaQueryWrapper<Project>().in(Project::getId, projectIdList));
        }
        projectFileDTOList = BeanCopyUtil.copyList(list, ProjectFileDTO.class);
        //1.2遍历项目根据项目id和学期id获取项目下的所有学生
        for (ProjectFileDTO projectFileDTO : projectFileDTOList) {
            Semester semester = semesterMapper.selectById(dto.getSemesterId());
            if (!ObjectUtils.isEmpty(semester)) {
                projectFileDTO.setSemesterName(semester.getName());
            }
            //1.2.1根据项目id和学期id获取项目下的所有学生
            List<StudentPageVO> studentPageVOList = projectMapper.selectStudentListByProjectIdAndSemesterId(projectFileDTO.getId(), dto.getSemesterId());
            projectFileDTO.setStudentPageVOList(studentPageVOList);
        }
        //1.3跟组织和学期查询所有学生的信息
        StudentPageDTO studentPageDTO = new StudentPageDTO();
        studentPageDTO.setSemesterId(dto.getSemesterId());
        studentPageDTO.setAgencyId(dto.getAgencyId());
        R<List<StudentPageVO>> studentResuslt = studentService.getStudentListByCondition(studentPageDTO);
        if (studentResuslt.failed()) {
            return R.Failed(studentResuslt.getMsg());
        }
        //2.创建Excel（路径，参数对象）
        String filePath = DEFAULT_FILE_PATH + StringConst.DEFAULT_PROJECT_PATH + "软件学院商业项目实作指导教师学生清单.xlsx";
        ExcelUtil.createProjectStudentListExcel(filePath, projectFileDTOList, studentResuslt.getData());
        return R.Success();
    }


    /**
     * 新增项目
     *
     * @param projectList
     */
    @Override
    public void insertProject(List<String> projectList) {
        for (String projectName : projectList) {
            if (ObjectUtils.isEmpty(getByProjectName(projectName))) {
                Project project = new Project();
                project.setProjectName(projectName);
                save(project);
            }
        }
    }
}
